const Phoenix = require('./phoenix');
import './lodash.min.js';

function getTopicRoom(topicDomain, topic) {
    var s = '';
    if (topic.args.length && topic.args.length != undefined) {
        s = topic.args.join('|');
    } else {
        s = _.map(topic.args || {}, function (v, k) {
            return k + '=' + v;
        }).join('|');
    }
    return ['topic', topicDomain, topic.id, s].join(':');
}

function subscribeTopic(url, domain, topics) {
    var topicSocket = new Phoenix.Socket(url, { params: { domain: domain } });
    topicSocket.connect();
    var subTopics = _.map(topics, function (topic) {
        var subTopic = { id: topic['id'], args: topic['args'] || [] };
        var topicName = getTopicRoom(domain, subTopic);
        var channel = topicSocket.channel(topicName, subTopic);
        channel
            .join()
            .receive('ok', function (resp) {
                console.log('Joined successfully');
                if (resp.body) {
                    topic['on_event'](resp.body);
                }
            })
            .receive('error', function (resp) {
                console.log('Unable to join', resp);
            });
        channel.on('message', function (event) {
            if (event.body) {
                topic['on_event'](event.body);
            }
        });
        return subTopic;
    });
}

export { subscribeTopic };
